package k8s

import (
	"errors"
	"gitee.com/hexug/go-tools/logger"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
)

var (
	// 获取原生的clientset
	GetClientSet               = getClientSet
	GetClientSetFromKubeConfig = getClientSetFromKubeConfig
)

// Move utility functions to a separate section for better organization
func getClientSet() (*kubernetes.Clientset, *rest.Config, error) {
	config, err := rest.InClusterConfig()
	if err != nil {
		logger.L().Infof("Get k8s in-cluster configuration failed. error: %v", err)
		logger.L().Info("Switching to out-of-cluster configuration")
		kubeconfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
			clientcmd.NewDefaultClientConfigLoadingRules(),
			&clientcmd.ConfigOverrides{},
		)
		config, err = kubeconfig.ClientConfig()
		if err != nil {
			logger.L().Errorf("Get k8s out-of-cluster configuration failed. error: %v", err)
			return nil, nil, errors.New("create k8s config failed")
		}
	}

	cs, err := kubernetes.NewForConfig(config)
	if err != nil {
		logger.L().Errorf("Get k8s in-cluster clientset failed. error: %v", err)
		return nil, config, errors.New("create k8s clientset failed")
	}

	return cs, config, nil
}

func getClientSetFromKubeConfig(kubeConfigPath string) (*kubernetes.Clientset, *rest.Config, error) {
	config, err := clientcmd.BuildConfigFromFlags("", kubeConfigPath)
	if err != nil {
		logger.L().Errorf("Get k8s configuration from kubeconfig failed. error: %s", err.Error())
		return nil, nil, errors.New("create k8s config failed")
	}
	if config == nil {
		logger.L().Errorf("Get k8s configuration from kubeconfig failed. kubeConfigPath is nil")
		return nil, nil, errors.New("create k8s config failed")
	}
	cs, err := kubernetes.NewForConfig(config)
	if err != nil {
		logger.L().Errorf("Get k8s clientset from kubeconfig failed. error: %v", err)
		return nil, config, errors.New("create k8s clientset failed")
	}

	return cs, config, nil
}
